const http = require('http');
const fs = require('fs');
const path = require('path');
const qs = require('querystring');
const server = http.createServer((req,res)=>{
    let  {url,method} = req
    console.log(url,method);
    if(method=='POST' && url.startsWith('/add') ){
        let allData = ''
        req.on('data',chuck => {
            allData += chuck.toString()
            //获取数据
        })
        req.on('end',()=>{
            console.log(decodeURI(allData));
            //使用qs.parse转成json字符串格式
            let jsObj = qs.parse(allData)
            console.log(jsObj);
            //找到当前数据的json字符串
            let dataStr = fs.readFileSync(path.join(__dirname,'db','data.json'),'utf-8')
            //转成数组 []
            let newArr =  JSON.parse(dataStr)  
            console.log(newArr);
             newArr.push(jsObj)
            console.log(newArr);
             let newJsonStirng = JSON.stringify(newArr);
             console.log(newJsonStirng);
            fs.writeFileSync(path.join(__dirname,'db','data.json'),newJsonStirng)
             res.end('ok')
        })
    }else{
        res.end('404')
    }
})
server.listen(8001,()=>{
    console.log('服务器已经开启');
})